package org.xx.armory.spring5.mvc.converters;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import java.util.Date;
import java.util.Set;

import static org.xx.armory.commons.StringConverter.parseLong;
import static org.xx.armory.commons.StringConverter.parseTimestampWithLeniency;

public class StringToDateConverter
        implements GenericConverter {
    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Set.of(new ConvertiblePair(String.class, Date.class));
    }

    @Override
    public Object convert(
            Object source,
            TypeDescriptor sourceType,
            TypeDescriptor targetType
    ) {
        final var s = source != null ? source.toString().strip() : "";
        final var type = targetType.getType();

        if (type.equals(Date.class)) {
            var d = parseTimestampWithLeniency(s, null);
            if (d == null) {
                var l = parseLong(s, null);
                if (l != null) {
                    d = new Date(l);
                }
            }
            return d;
        } else {
            assert false : "Illegal target type: " + targetType;
            return null;
        }
    }
}
